import type { ActionsTypes, Action, IState } from "../../types/users";

const initialState: IState = {
  users: JSON.parse(localStorage.getItem("users") ?? []),
};

export const usersReducer = (state: IState = initialState, action: Action): IState => {
  switch (action.type) {
    case ActionsTypes.CREATE_USER:
      localStorage.setItem("users", JSON.stringify([...state.users, action.payload]));
      return { users: [...state.users, action.payload] };

    case ActionsTypes.REMOVE_USER:
      const newUsers = [...state.users].filter((user) => user.id !== action.payload);
      localStorage.setItem("users", JSON.stringify(newUsers));
      return { users: newUsers };

    default:
      return state;
  }
};